<?php


namespace app\admin\controller;

use app\admin\model\NewsCommunication;
use app\admin\model\NewsCommunicationDetail;
use app\admin\model\NewsIssued;
use app\admin\model\NewsLetter;
use app\admin\model\Push;
use app\admin\model\WechatDepartment;
use app\admin\model\WechatDepartmentUser;
use app\admin\model\WechatUser;
use app\admin\model\WechatUserTag;
use com\wechat\TPQYWechat;
use think\Exception;
use think\Log;

/**
 * Class News
 * @package app\admin\controller
 * 文件上传下达
 */
class News extends Admin
{
    /**
     * 上级来文
     */
    public function communication()
    {
        $map = array(
            'status' => array('egt',0),
        );
        $search = input('search');
        //搜索
        if ($search != '') {
            $map['title'] = ['like', '%' . $search . '%'];
        }
        $list = NewsCommunication::where($map)->order('create_time desc')->paginate(10);
        int_to_string($list,['type' => ["1" => "行政","2" => "党建","3" => "工会","4" => "其它"]]);
        int_to_string($list,['status' => ["0" => "待分发","1" => "轮阅中","2" => "已归档"]]);
        $this->assign('list',$list);

        return $this->fetch();
    }

    /**
     * 上级来文新增
     */
    public function communicationadd()
    {
        $Model = new NewsCommunication();
        if(IS_POST) {
            $params = input('post.');
            $title = isset($params['title']) ? $params['title'] : null;
            $content = isset($params['content']) ? $params['content'] : null;
            $attachment = isset($params['attachment']) ? $params['attachment'] : null;
            if(empty($title) || empty($content)) {
                return $this->error("标题和内容必填，请校验");
            }
            $data = [];
            $data['title'] = $title;
            $data['content'] = $content;
            $data['create_user'] = $_SESSION['think']['user_auth']['id'];
            if(!empty($attachment)) {
                $data['attachment'] = json_encode($attachment);
            }
            $data['operate_user'] = WechatUserTag::getHeaderOfficeUser();
            $info = $Model->create($data);
            if($info) {
                //推送给办公室主任拟办
                $this->pushFile($info);
                //之前是推送总经理
//                $communication = $Model->where($data)->find();
//                $user = WechatUserTag::where(['tagid' => 1])->select();
//                foreach ($user as $value) {
//                    $data_detail = [
//                        'permission' => $value['tagid'],
//                        'userid' => $value['userid'],
//                        'communication_id' => $communication['id'],
//                        'status' => 0
//                    ];
//                    $res = NewsCommunicationDetail::where($data_detail)->find();
//                    if(!$res) {
//                       $push = NewsCommunicationDetail::create($data_detail);
//                       if($push) {
//                           $this->pushFile($push);
//                       }
//                    }
//                }
                return $this->success("新增成功",Url('News/communication'));
            }else{
                return $this->error($Model->getError());
            }
        }else{
            $this->default_pic();
            $this->assign('msg','');

            return $this->fetch('communicationedit');
        }
    }

    /**
     * 上级来文修改
     */
    public function communicationedit()
    {
        $Model = new NewsCommunication();
        if(IS_POST) {
            $data = input('post.');
            if(isset($data['attachment'])) {
                $data['attachment'] = json_encode($data['attachment']);
            }
            $data['operate_user'] = WechatUserTag::getHeaderOfficeUser();
            $info = $Model->validate('News.communication')->save($data,['id'=>input('id')]);
            if($info){
                return $this->success("修改成功",Url("News/communication"));
            }else{
                return $this->get_update_error_msg($Model->getError());
            }
        }else{
            $this->default_pic();
            $id = input('id');
            $msg = $Model->get($id);
            if($msg['attachment']) {
                $attachment = json_decode($msg['attachment']);
                $files = [];
                foreach ($attachment as $value) {
                    $files[] = \app\admin\model\File::get($value);
                }
                $msg['attachment_file'] = $files;
            }else {
                $msg['attachment_file'] = [];
            }
            $this->assign('msg',$msg);

            return $this->fetch();
        }
    }

    /**
     * 查看文件流转
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCommunicationList()
    {
        $id = input('id');
        $list = NewsCommunicationDetail::where('communication_id',$id)->select();
        foreach ($list as $key => $value) {
            $user = WechatUser::where('userid',$value['userid'])->find();
            $list[$key]['username'] = $user ? $user['name'] : "未定义";
            $list[$key]['remarks'] = $value['remarks'] ? $value['remarks'] : "无";
        }
        int_to_string($list,['status' => ["0" => "待分发","1" => "轮阅中","2" => "已归档","3" => "待阅读","4" => "已阅"]]);
        return $this->success("获取成功",'',$list);
    }

    /**
     * 上级来文
     */
    public function communicationdel()
    {
        $id = input('id');
        $data['status'] = '-1';
        $info = NewsCommunication::where('id',$id)->update($data);
        if($info) {
            NewsCommunicationDetail::where('communication_id',$id)->delete();
            return $this->success("删除成功");
        }else{
            return $this->error("删除失败");
        }
    }

    /**
     * 公司简讯
     */
    public function letter()
    {
        $map = array(
            'status' => array('egt',0),
        );
        $search = input('search');
        //搜索
        if ($search != '') {
            $map['title'] = ['like', '%' . $search . '%'];
        }
        $list = NewsLetter::where($map)->order('create_time desc')->paginate(10);
        $this->assign('list',$list);

        return $this->fetch();
    }

    /**
     * 简讯新增
     * @return mixed
     */
    public function letteradd()
    {
        $Model = new NewsLetter();
        if(IS_POST) {
            $data = input('post.');
            $data['create_user'] = $_SESSION['think']['user_auth']['id'];
            if(empty($data['id'])) {
                unset($data['id']);
            }
            $info = $Model->validate('News.letter')->save($data);
            if($info) {
                if($data['is_push'] == 1) {
                    $push = $Model->where($data)->find();
                    if($push) {
                        $this->pushNews(1,$push);
                    }
                }
                return $this->success("新增成功",Url('News/letter'));
            }else{
                return $this->error($Model->getError());
            }
        }else{
            $this->default_pic();
            $this->assign('msg','');

            return $this->fetch('letteredit');
        }
    }

    /**
     * 简讯修改
     * @return mixed
     */
    public function letteredit()
    {
        $Model = new NewsLetter();
        if(IS_POST) {
            $data = input('post.');
            $info = $Model->validate('News.letter')->save($data,['id'=>input('id')]);
            if($info){
                return $this->success("修改成功",Url("News/letter"));
            }else{
                return $this->get_update_error_msg($Model->getError());
            }
        }else{
            $this->default_pic();
            $id = input('id');
            $msg = $Model->get($id);
            $this->assign('msg',$msg);

            return $this->fetch();
        }
    }

    /**
     * 简讯删除
     * @return mixed
     */
    public function letterdel()
    {
        $id = input('id');
        $data['status'] = '-1';
        $info = NewsLetter::where('id',$id)->update($data);
        if($info) {
            return $this->success("删除成功");
        }else{
            return $this->error("删除失败");
        }
    }

    /**
     * 批量删除
     */
    public function letterMoveToTrash()
    {
        $ids = input('ids/a');
        if (!$ids) {
            return $this->error('请勾选删除选项');
        }
        $data['status'] = '-1';
        $info = NewsLetter::where('id', 'in', $ids)->update($data);

        if ($info) {
            return $this->success('批量删除成功', url('News/letter'));
        } else {
            return $this->error('批量删除失败');
        }
    }

    /**
     * 公司发文
     */
    public function issued()
    {
        $map = array(
            'status' => array('egt',0),
        );
        $search = input('search');
        //搜索
        if ($search != '') {
            $map['title'] = ['like', '%' . $search . '%'];
        }
        $list = NewsIssued::where($map)->order('create_time desc')->paginate(10);
        $status = [ 1 => "行政",2 => "党建", 3 => "工会"];
        foreach ($list as $value) {
            $value['type_text'] = $status[$value['type']];
        }
        $this->assign('list',$list);

        return $this->fetch();
    }

    /**
     * 发文新增
     * @return mixed
     */
    public function issuedadd()
    {
        $Model = new NewsIssued();
        if(IS_POST) {
            $data = input('post.');
            if(isset($data['attachment'])) {
                $data['attachment'] = json_encode($data['attachment']);
            }
            $data['create_user'] = $_SESSION['think']['user_auth']['id'];
            if(empty($data['id'])) {
                unset($data['id']);
            }
            $info = $Model->validate('News.issued')->save($data);
            if($info) {
                if($data['is_push'] == 1) {
                    $push = $Model->where($data)->find();
                    if($push) {
                        $this->pushNews(2,$push);
                    }
                }
                return $this->success("新增成功",Url('News/issued'));
            }else{
                return $this->error($Model->getError());
            }
        }else{
            $this->default_pic();
            $this->assign('msg','');

            return $this->fetch('issuededit');
        }
    }

    /**
     * 发文修改
     * @return mixed|void
     * @throws \think\Exception\DbException
     */
    public function issuededit()
    {
        $Model = new NewsIssued();
        if(IS_POST) {
            $data = input('post.');
            if(isset($data['attachment'])) {
                $data['attachment'] = json_encode($data['attachment']);
            }
            $info = $Model->validate('News.issued')->save($data,['id'=>input('id')]);
            if($info){
                return $this->success("修改成功",Url("News/issued"));
            }else{
                return $this->get_update_error_msg($Model->getError());
            }
        }else{
            $this->default_pic();
            $id = input('id');
            $msg = $Model->get($id);
            if($msg['attachment']) {
                $attachment = json_decode($msg['attachment']);
                $files = [];
                foreach ($attachment as $value) {
                    $files[] = \app\admin\model\File::get($value);
                }
                $msg['attachment_file'] = $files;
            }else {
                $msg['attachment_file'] = [];
            }
            $this->assign('msg',$msg);

            return $this->fetch();
        }
    }

    /**
     * 发文删除
     * @return mixed
     */
    public function issueddel()
    {
        $id = input('id');
        $data['status'] = '-1';
        $info = NewsIssued::where('id',$id)->update($data);
        if($info) {
            return $this->success("删除成功");
        }else{
            return $this->error("删除失败");
        }
    }

    /**
     * 批量删除
     */
    public function issuedMoveToTrash()
    {
        $ids = input('ids/a');
        if (!$ids) {
            return $this->error('请勾选删除选项');
        }
        $data['status'] = '-1';
        $info = NewsLetter::where('id', 'in', $ids)->update($data);

        if ($info) {
            return $this->success('批量删除成功', url('News/issued'));
        } else {
            return $this->error('批量删除失败');
        }
    }

    /**
     * 推送上级来文
     */
    private function pushFile($data){
        $communication = NewsCommunication::get(['id' => $data['id']]);
        $type = [1 => "[行政]", 2 => "[党建]", 3 => "[工会]", 4 => "[其它]"];
        $type_text = $type[$communication['type']];
        $send = [
            "title" => "您有新的上级来文需要拟办审核，请点击或前往个人中心->拟办意见列表查看！",
            'description' => "<div class=\"gray\">时间: ".date("Y-m-d H:i",time())."</div><div class=\"gray\">标题: ".$communication['title']."</div><div class=\"gray\">类型: ".$type_text."</div><div class=\"highlight\">点击查看</div>",
            "url" => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].'/home/documents/opinion_detail/id/'.$data['id']
//            "url" => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].'/home/documents/index.html',
        ];
        //发送给服务号
        $Wechat = new TPQYWechat(\think\Config::get('news'));
        $message = array(
            "touser" => 18768112486,
//            "touser" => $data['operate_user'],
            "msgtype" => 'textcard',
            "agentid" => config('news.agentid'),
            "textcard" => $send,
            "safe" => "0"
        );
        $data = [
            'type' => 2,
            'agentname' => "news",
            'touser' => $message['touser'],
            'msgtype' => $message['msgtype'],
            'agentid' => $message['agentid'],
            'sendcontent' => json_encode($message['textcard']),
            'safe' => $message['safe'],
        ];
        $res = Push::create($data);
        try {
            $msg = $Wechat->sendMessage($message);
            if ($msg['errcode'] == 0){
                Push::where('id',$res['id'])->update(['status' => 1]);
                Log::write("上级来文消息发送：发送成功:".$data['userid']);
            }else{
                Log::write("上级来文消息发送：发送失败:".$data['userid']);
            }
            Log::write($msg);
        }catch (Exception $exception) {
            $msg = $exception->getMessage();
            Log::write("上级来文消息发送：发送失败".$msg);
        }
    }

    /**
     * 新闻类消息推送
     * @param $type 1：公司简讯，2公司发文
     * @param $data
     * @throws Exception\DbException
     */
    private function pushNews($class,$data){
        if($class == 1) {
            $class_text = "【公司简讯】";
            $type_text = [1 => "[新闻]", 2 => "[通知]"];
            $url =  $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].'/home/news/detail/id/'.$data['id'];
            $send_type = "textcard";
            $send = [
                "title" => $class_text.$data['title'],
                'description' => "<div class=\"gray\">时间: ".date("Y-m-d H:i",time())."</div><div class=\"gray\">类型: ".$type_text[$data['type']]."</div><div class=\"highlight\">点击查看</div>",
                "url" => $url,
            ];
        }else {
            $class_text = "【公司发文】";
            $type_text = [1 => "[行政]", 2 => "[党建]", 3=> "[工会]"];
            $url =  $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].'/home/dispatch/detail/id/'.$data['id'];
            $send_type = "news";
            $send["articles"][0] = [
                "title" =>  $class_text.$data['title'],             //标题
                "description" => $type_text[$data['type']].substr(str_replace('&nbsp;','',strip_tags($data['content'])),0,100)."...", //描述
                "url" => $url,                 //点击后跳转的链接。可根据url里面带的code参数校验员工的真实身份。
            ];
            if(empty($data['front_cover'])) {
                $front_cover = [1 => "158", 2 => "159" , 3 => "160"];
                $send["articles"][0]['picurl'] = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].$this->get_cover($front_cover[$data['type']]);
            }else {
                $send["articles"][0]['picurl'] = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].$this->get_cover($data['front_cover']);//图文消息的图片链接,支持JPG、PNG格式，较好的效果为大图640*320，
            }
        }
        //发送给服务号
        $Wechat = new TPQYWechat(\think\Config::get('news'));
        $message = array(
            "msgtype" => $send_type,
            "agentid" => config('news.agentid'),
            $send_type => $send,
            "safe" => "0"
        );
        //发送全体排除离退休 测试 未加入部门成员
        $departments = WechatDepartment::where('id','not in',[1,34,39,40])->column('id');
        if(!empty($departments)) {
            $toParty = "34"; //测试部门
//            $toParty = implode('|',$departments);
            $message['toparty'] = $toParty;
        }else {
            $toUser = "18768112486";
//            $toUser = "@all";
            $message['touser'] = $toUser;
        }
        $data = [
            'type' => 2,
            'agentname' => "news",
            'touser' => isset($message['touser']) ? $message['touser'] : '',
            'toparty' => isset($message['toparty']) ? $message['toparty'] : '',
            'msgtype' => $message['msgtype'],
            'agentid' => $message['agentid'],
            'sendcontent' => json_encode($message[$send_type]),
            'safe' => $message['safe'],
        ];
        $res = Push::create($data);
        try {
            $msg = $Wechat->sendMessage($message);
            if ($msg['errcode'] == 0){
                Push::where('id',$res['id'])->update(['status' => 1]);
                Log::write("新闻消息发送：发送成功");
            }else{
                Log::write("新闻消息发送：发送失败");
            }
            Log::write($msg);
        }catch (Exception $exception) {
            $msg = $exception->getMessage();
            Log::write("新闻消息发送：发送失败".$msg);
        }
    }
}